<template>
  <div class="product-spec">
    <h3>填写商品属性/规格</h3>
    
    <div v-if="!categoryId" class="empty-tip">
      <el-empty description="请先选择商品类目" />
    </div>

    <div v-else class="spec-content">
      <!-- 商品属性规格 -->
      <div class="spec-section">
        <div class="section-title">
          <span>商品属性规格</span>
          <el-button
            text
            type="primary"
            @click="attrExpanded = !attrExpanded"
          >
            <el-icon>
              <component :is="attrExpanded ? 'ArrowUp' : 'ArrowDown'" />
            </el-icon>
            {{ attrExpanded ? '收起' : '展开' }}
          </el-button>
        </div>
        
        <el-collapse-transition>
          <div v-show="attrExpanded" class="attr-list">
            <el-row :gutter="20">
              <el-col
                v-for="attr in attributes"
                :key="attr.name"
                :span="12"
              >
                <div class="attr-item">
                  <span class="attr-name">{{ attr.name }}:</span>
                  <el-tag
                    v-for="value in attr.values"
                    :key="value"
                    size="small"
                    class="attr-value"
                  >
                    {{ value }}
                  </el-tag>
                </div>
              </el-col>
            </el-row>
          </div>
        </el-collapse-transition>
      </div>

      <!-- 商品销售价格属性 -->
      <div class="spec-section">
        <div class="section-title">商品销售价格属性</div>
        <div class="sale-attr-select">
          <el-checkbox-group v-model="selectedSaleAttrs" @change="handleSaleAttrChange">
            <el-checkbox
              v-for="attr in saleAttributes"
              :key="attr.name"
              :label="attr.name"
            >
              {{ attr.name }}
            </el-checkbox>
          </el-checkbox-group>
        </div>

        <!-- 属性值选择 -->
        <div v-if="selectedSaleAttrs.length > 0" class="attr-value-select">
          <div
            v-for="attrName in selectedSaleAttrs"
            :key="attrName"
            class="attr-value-item"
          >
            <span class="label">{{ attrName }}:</span>
            <el-checkbox-group
              v-model="selectedAttrValues[attrName]"
              @change="handleAttrValueChange"
            >
              <el-checkbox
                v-for="value in getAttrValues(attrName)"
                :key="value"
                :label="value"
              >
                {{ value }}
              </el-checkbox>
            </el-checkbox-group>
          </div>
        </div>
      </div>

      <!-- SKU列表 -->
      <div v-if="skuList.length > 0" class="sku-section">
        <div class="section-title">SKU列表</div>
        <el-table :data="skuList" border style="width: 100%">
          <!-- 动态属性列 -->
          <el-table-column
            v-for="attrName in selectedSaleAttrs"
            :key="attrName"
            :label="attrName"
            :prop="attrName"
            width="120"
          />
          
          <el-table-column label="销售价格" width="150" required>
            <template #default="scope">
              <el-input
                v-model="scope.row.salePrice"
                placeholder="价格"
                type="number"
                step="0.01"
                size="small"
              />
            </template>
          </el-table-column>

          <el-table-column label="商品库存" width="120" required>
            <template #default="scope">
              <el-input
                v-model="scope.row.stock"
                placeholder="库存"
                type="number"
                size="small"
              />
            </template>
          </el-table-column>

          <el-table-column label="单位" width="120" required>
            <template #default="scope">
              <el-select
                v-model="scope.row.stockUnit"
                placeholder="单位"
                size="small"
              >
                <el-option
                  v-for="unit in stockUnits"
                  :key="unit.value"
                  :label="unit.label"
                  :value="unit.value"
                />
              </el-select>
            </template>
          </el-table-column>

          <el-table-column label="库存预警值" width="130">
            <template #default="scope">
              <el-input
                v-model="scope.row.stockWarning"
                placeholder="预警值"
                type="number"
                size="small"
              />
            </template>
          </el-table-column>

          <el-table-column label="描述信息" width="150">
            <template #default="scope">
              <el-input
                v-model="scope.row.description"
                placeholder="描述"
                size="small"
              />
            </template>
          </el-table-column>

          <el-table-column label="仓库所在地" width="150" required>
            <template #default="scope">
              <el-select
                v-model="scope.row.warehouseLocation"
                placeholder="仓库"
                size="small"
              >
                <el-option
                  v-for="location in warehouseLocations"
                  :key="location.value"
                  :label="location.label"
                  :value="location.value"
                />
              </el-select>
            </template>
          </el-table-column>

          <el-table-column label="操作" width="80" fixed="right">
            <template #default="scope">
              <el-button
                type="danger"
                size="small"
                link
                @click="handleDeleteSku(scope.$index)"
              >
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, reactive, watch, computed } from 'vue'
import { ArrowUp, ArrowDown } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import { attributeData, stockUnits, warehouseLocations } from '../../utils/productMock'

export default {
  name: 'ProductSpec',
  components: {
    ArrowUp,
    ArrowDown
  },
  props: {
    modelValue: {
      type: Object,
      default: () => ({})
    },
    categoryId: {
      type: Number,
      default: null
    }
  },
  emits: ['update:modelValue'],
  setup(props, { emit }) {
    const attrExpanded = ref(true)
    const attributes = ref([])
    const saleAttributes = ref([])
    const selectedSaleAttrs = ref([])
    const selectedAttrValues = reactive({})
    const skuList = ref([])

    // 加载类目属性
    watch(() => props.categoryId, (newVal) => {
      if (newVal && attributeData[newVal]) {
        const categoryAttrs = attributeData[newVal]
        attributes.value = categoryAttrs.attributes
        saleAttributes.value = categoryAttrs.attributes.filter(attr => attr.isSaleAttr)
        
        // 重置选择
        selectedSaleAttrs.value = []
        Object.keys(selectedAttrValues).forEach(key => {
          delete selectedAttrValues[key]
        })
        skuList.value = []
      }
    }, { immediate: true })

    // 获取属性值
    const getAttrValues = (attrName) => {
      const attr = saleAttributes.value.find(a => a.name === attrName)
      return attr ? attr.values : []
    }

    // 销售属性变化
    const handleSaleAttrChange = (values) => {
      // 移除未选中属性的值
      Object.keys(selectedAttrValues).forEach(key => {
        if (!values.includes(key)) {
          delete selectedAttrValues[key]
        }
      })
      
      // 初始化新选中属性的值
      values.forEach(attrName => {
        if (!selectedAttrValues[attrName]) {
          selectedAttrValues[attrName] = []
        }
      })
      
      generateSkuList()
    }

    // 属性值变化
    const handleAttrValueChange = () => {
      generateSkuList()
    }

    // 生成SKU列表
    const generateSkuList = () => {
      if (selectedSaleAttrs.value.length === 0) {
        skuList.value = []
        updateModelValue()
        return
      }

      // 检查是否所有选中的属性都有值
      const hasAllValues = selectedSaleAttrs.value.every(attrName => {
        return selectedAttrValues[attrName] && selectedAttrValues[attrName].length > 0
      })

      if (!hasAllValues) {
        skuList.value = []
        updateModelValue()
        return
      }

      // 生成笛卡尔积
      const cartesian = (...arrays) => {
        return arrays.reduce((acc, array) => {
          return acc.flatMap(x => array.map(y => [...x, y]))
        }, [[]])
      }

      const attrValueArrays = selectedSaleAttrs.value.map(attrName => {
        return selectedAttrValues[attrName].map(value => ({
          attrName,
          value
        }))
      })

      const combinations = cartesian(...attrValueArrays)
      
      // 保留已有SKU的数据
      const existingSkuMap = new Map()
      skuList.value.forEach(sku => {
        const key = selectedSaleAttrs.value.map(attr => sku[attr]).join('_')
        existingSkuMap.set(key, sku)
      })

      skuList.value = combinations.map(combination => {
        const sku = {}
        combination.forEach(item => {
          sku[item.attrName] = item.value
        })
        
        // 尝试从已有数据恢复
        const key = selectedSaleAttrs.value.map(attr => sku[attr]).join('_')
        const existing = existingSkuMap.get(key)
        
        if (existing) {
          return { ...existing }
        }
        
        return {
          ...sku,
          salePrice: '',
          stock: '',
          stockUnit: '',
          stockWarning: '',
          description: '',
          warehouseLocation: ''
        }
      })

      updateModelValue()
    }

    // 删除SKU
    const handleDeleteSku = (index) => {
      skuList.value.splice(index, 1)
      updateModelValue()
      ElMessage.success('删除成功')
    }

    // 更新model值
    const updateModelValue = () => {
      emit('update:modelValue', {
        attributes: attributes.value,
        selectedSaleAttrs: selectedSaleAttrs.value,
        selectedAttrValues: { ...selectedAttrValues },
        skuList: skuList.value
      })
    }

    // 监听props变化
    watch(() => props.modelValue, (newVal) => {
      if (newVal && newVal.selectedSaleAttrs) {
        selectedSaleAttrs.value = newVal.selectedSaleAttrs
        Object.assign(selectedAttrValues, newVal.selectedAttrValues || {})
        skuList.value = newVal.skuList || []
      }
    }, { immediate: true, deep: true })

    // 监听skuList变化
    watch(skuList, () => {
      updateModelValue()
    }, { deep: true })

    return {
      attrExpanded,
      attributes,
      saleAttributes,
      selectedSaleAttrs,
      selectedAttrValues,
      skuList,
      stockUnits,
      warehouseLocations,
      getAttrValues,
      handleSaleAttrChange,
      handleAttrValueChange,
      handleDeleteSku
    }
  }
}
</script>

<style scoped>
.product-spec {
  padding: 20px;
}

.product-spec h3 {
  margin: 0 0 20px 0;
  font-size: 18px;
  color: #303133;
}

.empty-tip {
  padding: 50px 0;
}

.spec-content {
  max-width: 100%;
}

.spec-section {
  margin-bottom: 30px;
  padding: 20px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.section-title {
  font-size: 16px;
  font-weight: 500;
  color: #303133;
  margin-bottom: 15px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.attr-list {
  padding: 15px 0;
}

.attr-item {
  margin-bottom: 15px;
  display: flex;
  align-items: flex-start;
}

.attr-name {
  font-weight: 500;
  color: #606266;
  min-width: 80px;
  margin-right: 10px;
}

.attr-value {
  margin-right: 8px;
  margin-bottom: 8px;
}

.sale-attr-select {
  margin-bottom: 20px;
}

.attr-value-select {
  margin-top: 20px;
}

.attr-value-item {
  margin-bottom: 15px;
  display: flex;
  align-items: flex-start;
}

.attr-value-item .label {
  font-weight: 500;
  color: #606266;
  min-width: 100px;
  margin-right: 15px;
  padding-top: 5px;
}

.sku-section {
  margin-top: 20px;
}
</style>
